package com.wemei.auto.api.core

import android.util.Log
import com.squareup.moshi.FromJson
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.ConnectionPool
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.IOException
import java.math.BigDecimal
import java.util.concurrent.TimeUnit

val MOSHI = Moshi.Builder()
    .add(BigDecimalTypeAdapter())
    .add(KotlinJsonAdapterFactory())
    .build()

class BigDecimalTypeAdapter {
    @FromJson
    @Throws(IOException::class)
    fun fromJson(value: String): BigDecimal {
        return BigDecimal(value)
    }
    @ToJson
    fun toJson(value: BigDecimal?): String? {
        return value?.toPlainString()
    }
}
/**
 *   @auther : zhoucl
 *   time   : 2017/09/04
 */
object ApiHelper {
    private val dispatcher: Dispatcher = Dispatcher()
    private val connectionPool: ConnectionPool = ConnectionPool()
    private const val TIME_OUT = 60L * 2
    private var SHOW_LOGGER: Boolean = true
    fun initHttp(showLogger: Boolean = true) {
        SHOW_LOGGER = showLogger
    }

    fun <T> create(
        clazz: Class<T>,
        configRetrofit: (Retrofit.Builder.() -> Unit),
        configOkHttp: (OkHttpClient.Builder.() -> Unit)? = null,
    ): T = Retrofit.Builder()
        .client(OkHttpClient.Builder()
            .connectionPool(connectionPool)
            .dispatcher(dispatcher)
            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(TIME_OUT, TimeUnit.SECONDS)
            //.proxy(Proxy.NO_PROXY)
            .apply {
                if (configOkHttp != null) {
                    this.configOkHttp()
                }
//                if (SHOW_LOGGER) {
//                    addInterceptor(getHttpLoggingInterceptor())
//                }
            }
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .build())
        .addConverterFactory(MoshiConverterFactory.create(MOSHI))
//            .addConverterFactory(FastJsonConverterFactory.create())
//            .addCallAdapterFactory(CoreCallAdapterFactory.create(WrapResultBean::class.java))
        .apply(configRetrofit)
        .build()
        .create(clazz)

    fun getHttpLoggingInterceptor() =
        HttpLoggingInterceptor {
            Log.e("Logger", "Api请求==>$it")
        }.apply {
            setLevel(HttpLoggingInterceptor.Level.BODY)
        }
}